package com.simon.mynotes;

import com.simon.dao.NoteRepository;
import com.simon.notes.model.NotesModel;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AddNote extends Activity {

	private EditText topicField;
	private EditText noteField;
	private Button saveButton;

	// Database
	private NoteRepository repos;

	NotesModel modifModel = new NotesModel();

	boolean isModified = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_note);

		Bundle extras = getIntent().getExtras();

		topicField = (EditText) findViewById(R.id.topicField);
		noteField = (EditText) findViewById(R.id.noteField);
		saveButton = (Button) findViewById(R.id.buttonField);
		repos = new NoteRepository(this);
		noteField.setSelection(0);

		if (extras != null) {
			modifModel = (NotesModel) extras.getSerializable("model");
			isModified = true;
			update(modifModel);
		}

	}

	private void update(NotesModel model) {
		topicField.setText(model.getTopic());
		noteField.setText(model.getNote());
	}

	public void saveNote(View v) {
		if (!isModified) {
			NotesModel model = new NotesModel();
			model.setDate(System.currentTimeMillis() + "");
			model.setTopic(topicField.getText().toString());
			model.setNote(noteField.getText().toString());
			repos.create(model);
		}
		this.finish();
	}

	@Override
	public void finish() {

		Intent intent = new Intent();
		modifModel.setTopic(topicField.getText().toString());
		modifModel.setNote(noteField.getText().toString());

		intent.putExtra("returnModel", modifModel);
		setResult(RESULT_OK, intent);
		super.finish();
	}
}
